// 注意：实际项目中需要使用axios进行API调用
import axios from 'axios';
import { Character, SearchResult, CharacterCreate, CharacterUpdate } from '../types';

// 创建axios实例，配置基础URL
const api = axios.create({
  baseURL: 'http://localhost:8000/api', // 后端API的基础URL
  timeout: 30000, // 增加超时时间到30秒以解决对话超时问题
  headers: {
    'Content-Type': 'application/json'
  }
});

/**
 * 角色服务接口
 * 提供与角色相关的所有API调用方法
 */
const characterService = {
  /**
 * 获取所有角色列表
 * @returns Promise<Character[]>
 * @接口文档: GET /api/characters
 * @返回示例: [
 *   {
 *     "id": "harry-potter",
 *     "name": "哈利波特",
 *     "nameEn": "Harry Potter",
 *     "avatar": "...",
 *     "description": "...",
 *     "background": "...",
 *     "language": ["英语","中文"],
 *     "personality": ["勇敢","善良"],
 *     "skills": [
 *       {"id":"1","name":"魔法咒语","description":"..."}
 *     ]
 *   }
 * ]
 */
async getAllCharacters(): Promise<Character[]> {
  try {
    const response = await api.get('/characters');
    // 确保返回的数据是数组
    const charactersData = Array.isArray(response.data) ? response.data : [];
    
    // 处理字段映射，确保name_en映射到nameEn
    return charactersData.map(character => ({
      ...character,
      nameEn: character.nameEn || character.name_en || ''
    }));
  } catch (error) {
    console.error('获取角色列表失败:', error);
    throw error;
  }
},

  /**
   * 根据角色ID获取角色详情
   * @param characterId 角色唯一标识
   * @returns Promise<Character | null>
   * @接口文档: GET /api/characters/:id
   * @返回示例: {"id":"string","name":"string","nameEn":"string","avatar":"string","description":"string","background":"string","language":[],"personality":[],"skills":[]}
   */
async getCharacterById(characterId: string): Promise<Character | null> {
  try {
    const response = await api.get(`/characters/${characterId}`);
    // 处理字段映射，确保name_en映射到nameEn
    if (response.data) {
      return {
        ...response.data,
        nameEn: response.data.nameEn || response.data.name_en || ''
      };
    }
    return null;
  } catch (error) {
    console.error(`获取角色ID为${characterId}的详情失败:`, error);
    throw error;
  }
},

  /**
   * 搜索角色
   * @param query 搜索关键词
   * @returns Promise<SearchResult>
   * @接口文档: GET http://localhost:8000/api/characters/search?query=关键词
   * @返回示例: {"characters":[{"id":"string","name":"string","nameEn":"string","avatar":"string","description":"string","background":"string","language":[],"personality":[],"skills":[]}],"total":1}
   * @示例: curl "http://localhost:8000/api/characters/search?query=哈利"
   */
async searchCharacters(query: string): Promise<SearchResult> {
  try {
    const response = await api.get(`/characters/search?query=${encodeURIComponent(query)}`);
    
    // 确保结果格式正确并处理字段映射
    const resultData = response.data || { characters: [], total: 0 };
    const characters = Array.isArray(resultData.characters) ? resultData.characters : [];
    
    // 处理每个角色的字段映射
    const mappedCharacters = characters.map((character: any) => ({
        ...character,
      nameEn: character.nameEn || character.name_en || ''
    }));
    
    return {
      characters: mappedCharacters,
      total: resultData.total || mappedCharacters.length
    };
  } catch (error) {
    console.error('搜索角色失败:', error);
    // 返回空结果而不是抛出错误
    return { characters: [], total: 0 };
  }
},

  /**
   * 获取角色对话回复
   * @param characterId 角色ID
   * @param message 用户消息
   * @param context 对话上下文（可选）
   * @returns Promise<string> 角色回复内容
   * @接口文档: POST http://localhost:8000/api/characters/:id/chat
   * @请求头: Content-Type: application/json
   * @请求体: {"message":"用户消息","context":[对话上下文数组]}
   * @返回示例: "角色回复内容"
   * @示例: curl -X POST "http://localhost:8000/api/characters/harry-potter/chat" -H "Content-Type: application/json" -d '{"message": "今天魁地奇训练怎么样？", "context": ["我们刚在霍格沃茨见面"]}'
   */
  async getCharacterResponse(
    characterId: string,
    message: string,
    _context?: string[]
  ): Promise<string> {
    // 注意：_context参数用于传递对话历史上下文，在实际项目中会被传递给后端API
    try {
      const response = await api.post(`/characters/${characterId}/chat`, {
        message,
        context: _context || []
      });
      return response.data;
    } catch (error) {
      console.error(`获取角色ID为${characterId}的回复失败:`, error);
      throw error;
    }
  },

  /**
   * 创建新角色（自动维护语言/性格/技能关联）
   * @param characterData 角色创建数据
   * @returns Promise<Character> 创建成功的角色对象
   * @接口文档: POST /api/characters
   * @请求头: Content-Type: application/json
   * @请求体: {
   *   "id": "new-hero",
   *   "name": "新英雄",
   *   "nameEn": "New Hero",
   *   "avatar": null,
   *   "description": "一个新的测试角色",
   *   "background": "背景故事……",
   *   "language": ["中文","英语"],
   *   "personality": ["勇敢","冷静"],
   *   "skills": [
   *     {"name":"疾风步","description":"快速移动"},
   *     {"name":"盾墙","description":"强力防御"}
   *   ]
   * }
   * @返回示例: {
   *   "id": "new-hero",
   *   "name": "新英雄",
   *   "nameEn": "New Hero",
   *   "avatar": null,
   *   "description": "一个新的测试角色",
   *   "background": "背景故事……",
   *   "language": ["中文","英语"],
   *   "personality": ["勇敢","冷静"],
   *   "skills": [
   *     {"id":"1","name":"疾风步","description":"快速移动"},
   *     {"id":"2","name":"盾墙","description":"强力防御"}
   *   ]
   * }
   */
  async createCharacter(characterData: CharacterCreate): Promise<Character> {
    try {
      const response = await api.post('/characters', characterData);
      // 确保返回的数据符合Character类型，并处理字段映射
      if (response.data) {
        return {
          ...response.data,
          nameEn: response.data.nameEn || response.data.name_en || ''
        };
      }
      throw new Error('创建角色失败：返回数据为空');
    } catch (error) {
      console.error('创建角色失败:', error);
      throw error;
    }
  },

  /**
   * 更新角色信息
   * @param characterId 角色ID
   * @param updateData 更新的角色数据（部分字段可选）
   * @returns Promise<Character> 更新后的角色对象
   * @接口文档: PUT /api/characters/{id}
   * @请求体示例:
   * {
   *   "name": "更新后的名字",
   *   "description": "更新后的描述",
   *   "background": "更新后的背景故事……",
   *   "language": ["中文"],
   *   "personality": ["坚韧"],
   *   "skills": [{"name":"盾墙","description":"强力防御"}]
   * }
   */
  async updateCharacter(characterId: string, updateData: CharacterUpdate): Promise<Character> {
    try {
      const response = await api.put(`/characters/${characterId}`, updateData);
      
      // 确保返回的数据符合Character类型，并处理字段映射
      if (response.data) {
        return {
          ...response.data,
          nameEn: response.data.nameEn || response.data.name_en || ''
        };
      }
      throw new Error('更新角色失败：返回数据为空');
    } catch (error) {
      console.error('更新角色失败:', error);
      throw error;
    }
  },

  /**
   * 删除角色（级联清理关联）
   * @param characterId 角色ID
   * @returns Promise<void>
   * @接口文档: DELETE /api/characters/{id}
   */
  async deleteCharacter(characterId: string): Promise<void> {
    try {
      await api.delete(`/characters/${characterId}`);
      // 删除成功，无需返回数据
    } catch (error) {
      console.error('删除角色失败:', error);
      throw error;
    }
  }
};

export default characterService;